<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="2-10个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option
          v-for="item in employees"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>

</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import { addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'

export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 验证部门编码是否重复
    const validCode = (rules, value, callback) => {
      console.log(this.originList.map(item => item.code))
      let existCodeList = this.originList.map(item => item.code)
      if (this.isEdit) {
        // this.originList.map(item => item.code) 使用filter排除自己并且获取所有
        existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      existCodeList.includes(value) ? callback(new Error('部门编码已存在'))
        : callback()
    }
    // 验证部门编码是否重复
    const validName = (rules, value, callback) => {
      // 判断逻辑
      // 找到当前部门所有的子部门 --> 得到被占用的列表
      let existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      // 通过当前的id去找父级，再找所有的儿子和兄弟(包括自己) --> 再排除自己
      if (this.isEdit) {
        const pid = this.originList.find(item => item.id === this.id).pid
        existNameList = this.originList
          .filter(item => item.pid === pid) // 通过pid找到所有兄弟(包括自己)并返回一个新数组
          .filter(item => item.id !== this.id) // 在所有兄弟中排除自己并返回一个新数组
          .map(item => item.name) // map获取只包含name的数组
      }
      existNameList.includes(value) ? callback(new Error('此部门已存在'))
        : callback()
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门负责人
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称要求为2 ~ 10', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ], // 部门名称
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求为1 ~ 50', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ], // 部门编码
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ], // 部门负责人
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求为1 ~ 300', trigger: 'blur' }
        ] // 部门介绍
      },
      employees: []
    }
  },
  /*
  解决方案3：在组件内监听id的变化

  watch: {
    // 'id': {
    //   handler: function(newVal, oldVal) {
    //     console.log('id变了！ 新值：', newVal, '旧值', oldVal)
    //     // 重发请求获取详情
    //     this.loadDepartmentDetailById()
    //   },
    //   immediate: true
    // }
    'id': function(newVal, oldVal) {
      console.log('id变了！ 新值：', newVal, '旧值', oldVal)
      // 重发请求获取详情
      this.loadDepartmentsDetail()
    }
  },
  */
  created() {
    this.loadEmployeeSimple()
    if (this.isEdit) {
      this.loadDepartmentsDetail()
    }
  },
  methods: {
    resetForm() {
      this.$refs.deptForm.resetFields()
      // console.log('resetForm')
    },
    // 根据id查询指定部门信息
    async loadEmployeeSimple() {
      try {
        const { data: res } = await getEmployeeSimple()
        console.log('获取下拉员工数据', res)
        this.employees = res
      } catch (error) {
        console.log(error)
      }
    },
    async doAdd() {
      try {
        const res = await addDepartments({ pid: this.id, ...this.form })
        console.log(res)
        // this.$emit('父组件的事件')
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取当前部门的详情
    async loadDepartmentsDetail() {
      try {
        const res = await getDepartDetail(this.id)
        console.log('编辑', res)
        this.form = res.data
      } catch (error) {
        console.log(error)
      }
    },
    async doEdit() {
      try {
        const res = await updateDepartments({ id: this.id, ...this.form })
        console.log('修改数据成功', res)
        // 关闭对话框，刷新页面
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 确定
    hSubmit() {
      // 先省略表单验证
      // 根据 isEdit的值，决定做保存还是添加
      // if (this.isEdit) {
      //   this.doEdit()
      // } else {
      //   this.doAdd()
      // }
      // 完成表单效验
      this.$refs.deptForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 取消
    hCancel() {
      this.$refs.deptForm.resetFields()
      this.$emit('close')
    }
  }
}
</script>

<style>

</style>
